﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartMathLibrary.LinearEquationSolvers.Preconditioners
{
    /// <summary>
    /// This class represents a Jin-Wei-Tam preconditioner.
    /// </summary>
    [Serializable]
    public class JinWeiTamPreconditioner : IPreconditioner
    {
        /// <summary>
        /// The source matrix for the precondition process.
        /// </summary>
        private SquareMatrix sourceMatrix;

        /// <summary>
        /// Initializes a new instance of the <see cref="JinWeiTamPreconditioner"/> class.
        /// </summary>
        /// <param name="sourceMatrix">The source matrix for the precondition process.</param>
        public JinWeiTamPreconditioner(SquareMatrix sourceMatrix)
        {
            if (sourceMatrix == (SquareMatrix) null)
            {
                throw new ArgumentNullException("sourceMatrix");
            }

            this.sourceMatrix = sourceMatrix;
        }

        /// <summary>
        /// Gets or sets the source matrix for the precondition process.
        /// </summary>
        /// <value>The source matrix for the precondition process.</value>
        public SquareMatrix SourceMatrix
        {
            get { return sourceMatrix; }
            set { sourceMatrix = value; }
        }

        /// <summary>
        /// Computes the precondition matrix of the specified matrix.
        /// </summary>
        /// <returns>
        /// The computed precondition matrix of the original matrix.
        /// </returns>
        public Matrix ComputePreconditionMatrix()
        {
            double a = 0;
            Matrix result = new Matrix(this.sourceMatrix.Rows, this.sourceMatrix.Columns);

            for (int i = 0; i < this.sourceMatrix.Rows; i++)
            {
                for (int j = 0; j < this.sourceMatrix.Columns; j++)
                {
                    a += this.sourceMatrix.GetValueAtPosition(i, j);
                }
            }

            double inverseA = 1/a;

            for (int i = 0; i < this.sourceMatrix.Rows; i++)
            {
                for (int j = 0; j < this.sourceMatrix.Columns; j++)
                {
                    if (i == j)
                    {
                        result.SetValueAtPosition(i, j, inverseA + (1/this.sourceMatrix.GetValueAtPosition(i, i)));
                    }
                    else
                    {
                        result.SetValueAtPosition(i, j, inverseA);
                    }
                }
            }

            return result;
        }
    }
}